<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch" label-width="68px">
      <el-form-item label="算法名称" prop="algorithmName">
        <el-input
          v-model="queryParams.algorithmName"
          placeholder="请输入算法名称"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="算法作者" prop="algorithmAuthor">
        <el-input
          v-model="queryParams.algorithmAuthor"
          placeholder="请输入算法作者"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="模块类型" prop="moduleType">
        <el-select v-model="queryParams.moduleType" placeholder="请选择模块类型" clearable>
          <el-option
            v-for="dict in dict.type.module_type"
            :key="dict.value"
            :label="dict.label"
            :value="dict.value"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="算法类型" prop="algorithmType">
        <el-select v-model="queryParams.algorithmType" placeholder="请选择算法类型" clearable>
          <el-option
            v-for="dict in dict.type.algorithm_type"
            :key="dict.value"
            :label="dict.label"
            :value="dict.value"
          />
        </el-select>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="el-icon-plus"
          size="mini"
          @click="handleAdd"
          v-hasPermi="['system:algorithm:add']"
        >新增</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="success"
          plain
          icon="el-icon-edit"
          size="mini"
          :disabled="single"
          @click="handleUpdate"
          v-hasPermi="['system:algorithm:edit']"
        >修改</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="danger"
          plain
          icon="el-icon-delete"
          size="mini"
          :disabled="multiple"
          @click="handleDelete"
          v-hasPermi="['system:algorithm:remove']"
        >删除</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="warning"
          plain
          icon="el-icon-download"
          size="mini"
          @click="handleExport"
          v-hasPermi="['system:algorithm:export']"
        >导出</el-button>
      </el-col>
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="algorithmList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="序号" type="index" width="50"/>
      <el-table-column label="算法编码" align="center" prop="algorithmCode" width="130" show-overflow-tooltip />
      <el-table-column label="算法名称" align="center" prop="algorithmName" width="130" show-overflow-tooltip />
      <el-table-column label="算法作者" align="center" prop="algorithmAuthor" />
      <el-table-column label="模块类型" align="center" prop="moduleType" width="160" show-overflow-tooltip>
        <template slot-scope="scope">
          <dict-tag :options="dict.type.module_type" :value="scope.row.moduleType"/>
        </template>
      </el-table-column>
      <el-table-column label="算法类型" align="center" prop="algorithmType" width="160" show-overflow-tooltip>
        <template slot-scope="scope">
          <dict-tag :options="dict.type.algorithm_type" :value="scope.row.algorithmType"/>
        </template>
      </el-table-column>
      <el-table-column label="调用次数" align="center" prop="callCount" />
      <el-table-column label="调用时间" align="center" prop="callTime" width="180">
        <template slot-scope="scope">
          <span>{{ parseTime(scope.row.callTime, '{y}-{m}-{d} {h}:{i}:{s}') }}</span>
        </template>
      </el-table-column>
      <el-table-column label="算法版本" align="center" prop="algorithmVersion" />
      <el-table-column label="状态" align="center" prop="status">
        <template slot-scope="scope">
          <el-switch
            v-model="scope.row.status"
            active-value="0"
            inactive-value="1"
            @change="handleStatusChange(scope.row)"
          ></el-switch>
        </template>
      </el-table-column>
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template slot-scope="scope">
          <el-button
            size="mini"
            type="text"
            icon="el-icon-edit"
            @click="handleUpdate(scope.row)"
            v-hasPermi="['system:algorithm:edit']"
          >修改</el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-delete"
            @click="handleDelete(scope.row)"
            v-hasPermi="['system:algorithm:remove']"
          >删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination
      v-show="total>0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 添加或修改Python算法对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="800px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="80px">
        <el-row>
          <el-col :span="12">
            <el-form-item label="算法编码" prop="algorithmCode">
              <el-input v-model="form.algorithmCode" placeholder="请输入算法编码" :disabled="form.algorithmId != null" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="算法名称" prop="algorithmName">
              <el-input v-model="form.algorithmName" placeholder="请输入算法名称" />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="12">
            <el-form-item label="算法作者" prop="algorithmAuthor">
              <el-input v-model="form.algorithmAuthor" placeholder="请输入算法作者" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="模块类型" prop="moduleType">
              <el-select v-model="form.moduleType" placeholder="请选择模块类型" style="width: 100%">
                <el-option
                  v-for="dict in dict.type.module_type"
                  :key="dict.value"
                  :label="dict.label"
                  :value="dict.value"
                ></el-option>
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="24">
            <el-form-item label="算法类型" prop="algorithmType">
              <el-select v-model="form.algorithmType" placeholder="请选择算法类型" style="width: 100%">
                <el-option
                  v-for="dict in dict.type.algorithm_type"
                  :key="dict.value"
                  :label="dict.label"
                  :value="dict.value"
                ></el-option>
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="12">
            <el-form-item prop="deploymentMode" label-width="98px">
              <span slot="label">
                <el-tooltip content="自动部署上传部署文件，手动部署填写绝对路径如:`/home/www/test.py`" placement="top">
                <i class="el-icon-question"></i>
                </el-tooltip>
                部署方式
              </span>
              <el-radio-group v-model="form.deploymentMode">
                <el-radio label="0">自动部署</el-radio>
                <el-radio label="1">手动部署</el-radio>
              </el-radio-group>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item prop="paramsType" label-width="98px">
              <span slot="label">
                <el-tooltip content="参数类型分单个参数、多个参数" placement="top">
                <i class="el-icon-question"></i>
                </el-tooltip>
                参数类型
              </span>
              <el-radio-group v-model="form.paramsType">
                <el-radio label="0">单个</el-radio>
                <el-radio label="1">多个</el-radio>
              </el-radio-group>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="12">
            <el-form-item prop="fileName">
              <span slot="label">
                <el-tooltip content="如：test.py" placement="top">
                <i class="el-icon-question"></i>
                </el-tooltip>
                文件名
              </span>
              <el-input v-model="form.fileName" placeholder="请输入文件名" :disabled="form.deploymentMode === '0'" />
            </el-form-item>
          </el-col>
          <el-col :span="12" v-if="form.deploymentMode === '0'">
            <el-form-item label="上传文件" prop="relativePath">
              <file-upload :limit="1" :file-type="['py']" @multipleInput="getFileUpload" :open-time="new Date().getTime()"/>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="24">
            <el-form-item label="绝对路径" prop="absolutePath">
              <el-input v-model="form.absolutePath" placeholder="请输入绝对路径" :disabled="form.deploymentMode === '0'" />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="24">
            <el-form-item label="备注" prop="remark">
              <el-input v-model="form.remark" type="textarea" placeholder="请输入内容" maxlength="255" show-word-limit />
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { listAlgorithm, getAlgorithm, delAlgorithm, addAlgorithm, updateAlgorithm } from "@/api/system/algorithm";
import { changeUserStatus } from '@/api/system/user'

export default {
  name: "Algorithm",
  dicts: ['module_type', 'algorithm_type'],
  data() {
    return {
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // Python算法表格数据
      algorithmList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        algorithmCode: null,
        algorithmName: null,
        algorithmAuthor: null,
        moduleType: null,
        algorithmType: null,
        fileName: null,
      },
      // 表单参数
      form: {},
      // 表单校验
      rules: {
        algorithmCode: [
          { required: true, message: "算法编码不能为空", trigger: "blur" }
        ],
        algorithmName: [
          { required: true, message: "算法名称不能为空", trigger: "blur" }
        ],
        algorithmAuthor: [
          { required: true, message: "算法作者不能为空", trigger: "blur" }
        ],
        moduleType: [
          { required: true, message: "模块类型不能为空", trigger: "change" }
        ],
        algorithmType: [
          { required: true, message: "算法类型不能为空", trigger: "change" }
        ],
        deploymentMode: [
          { required: true, message: "部署方式不能为空", trigger: "change" }
        ],
        paramsType: [
          { required: true, message: "参数类型不能为空", trigger: "change" }
        ],
      }
    };
  },
  created() {
    this.getList();
  },
  methods: {
    /** 查询Python算法列表 */
    getList() {
      this.loading = true;
      listAlgorithm(this.queryParams).then(response => {
        this.algorithmList = response.rows;
        this.total = response.total;
        this.loading = false;
      });
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {
        algorithmId: null,
        algorithmCode: null,
        algorithmName: null,
        algorithmAuthor: null,
        moduleType: null,
        algorithmType: null,
        deploymentMode: "0",
        paramsType: "0",
        fileName: null,
        relativePath: null,
        absolutePath: null,
        fileUrl: null,
        fileSize: null,
        callCount: null,
        callTime: null,
        algorithmVersion: null,
        status: "0",
        createBy: null,
        createTime: null,
        updateBy: null,
        updateTime: null,
        remark: null
      };
      this.resetForm("form");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.algorithmId)
      this.single = selection.length!==1
      this.multiple = !selection.length
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset();
      this.open = true;
      this.title = "添加Python算法";
    },
    handleStatusChange(row) {
      let text = row.status === "0" ? "启用" : "停用";
      this.$modal.confirm('确认要"' + text + '""' + row.algorithmName + '"吗？').then(function() {
        let statusData = {
          algorithmId: row.algorithmId,
          status: row.status
        }
        return updateAlgorithm(statusData);
      }).then(() => {
        this.$modal.msgSuccess(text + "成功");
      }).catch(function() {
        row.status = row.status === "0" ? "1" : "0";
      });
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset();
      const algorithmId = row.algorithmId || this.ids
      getAlgorithm(algorithmId).then(response => {
        this.form = response.data;
        this.open = true;
        this.title = "修改Python算法";
      });
    },
    getFileUpload(res) {
      if (res.length > 0) {
        let file = res[0]
        this.form.fileName = file.originalFilename
        this.form.relativePath = file.fileName
        this.form.absolutePath = file.absolutePath
        this.form.fileUrl = file.url
        this.form.fileSize = file.fileSize
      }
    },
    /** 提交按钮 */
    submitForm() {
      this.$refs["form"].validate(valid => {
        if (valid) {
          if (this.form.algorithmId != null) {
            updateAlgorithm(this.form).then(response => {
              this.$modal.msgSuccess("修改成功");
              this.open = false;
              this.getList();
            });
          } else {
            addAlgorithm(this.form).then(response => {
              this.$modal.msgSuccess("新增成功");
              this.open = false;
              this.getList();
            });
          }
        }
      });
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const algorithmIds = row.algorithmId || this.ids;
      this.$modal.confirm('是否确认删除Python算法编号为"' + algorithmIds + '"的数据项？').then(function() {
        return delAlgorithm(algorithmIds);
      }).then(() => {
        this.getList();
        this.$modal.msgSuccess("删除成功");
      }).catch(() => {});
    },
    /** 导出按钮操作 */
    handleExport() {
      this.download('system/algorithm/export', {
        ...this.queryParams
      }, `algorithm_${new Date().getTime()}.xlsx`)
    }
  }
};
</script>
